from scapy.all import *
from socket import *
import netifaces
import time

start_scan = 2
end_scan = 4


# 调用netifices自动扫描ip地址——需要返回一个ip地址列表
# def get_gateways():
#     return netifaces.gateways()['default'][netifaces.AF_INET][0]

# 调用netifices自动扫描ip地址——需要返回一个ip地址列表
def get_selfip_list():
    import re
    with open("/etc/hosts", 'r') as f:
        s = f.read()
        lst = s.split("\n")
        #	print(lst)
        nlst = []
    for k in lst:
        if '#' in k:
            continue
        elif "ip6" in k:
            continue
        elif "127" in k:
            continue
        elif "::" in k:
            continue
        elif not k:
            continue
        else:
            nlst.append(re.split("\t|\s|\n", k.strip())[0])
    return nlst


print(get_selfip_list())


# 将若干个ip地址分别生成n个网段中所有ip地址的列表ip_list，将这些列表作为ip_lists的元素
def get_ip_lists(ips):
    ip_lists = []
    for ip in ips:
        ip_list = []
        for i in range(start_scan, end_scan):
            ip_list.append('{}{}'.format(ip[:-1], i))
        ip_lists.append(ip_list)
    return ip_lists


# 通过ARP扫描发现主机是否存活
def arp_scan(ip):
    p = ARP(pdst=ip)
    ans = sr1(p, timeout=1)
    if ans != None:
        # ans.display()
        # print(ip,"host is up.")
        return ans
    else:
        # print(ip,"host is down.")
        return None


# 扫描存活主机
def get_alive_Hosts(ips=None):
    ips = get_selfip_list()
    ip_lists = get_ip_lists(ips)
    for i in range(len(ips)):
        temp_ip_list = []
        ip = ips[i]
        print("Scanning the network from ip:", ip)
        hosts = ip[:-1] + '0/24'
        print('Scanning time:' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
        for ip in ip_lists[i]:
            if arp_scan(ip) == None:
                temp_ip_list.append(ip)
        print(str(hosts) + ' 网络中的存活主机:')
        for ip in temp_ip_list: ip_lists[i].remove(ip)
        for ip in ip_lists[i]: print(ip)
    return ip_lists  # [[]]


# 扫描指定ip的指定端口是否开放
def scan_port(host, port):
    target_ip = gethostbyname(host)
    sock = socket(AF_INET, SOCK_STREAM)
    sock.settimeout(6)
    result = sock.connect_ex((target_ip, port))
    print("type!!!!!!!!", type(result))
    print(result)
    if result == 0:
        # print('[*] port '+str(port)+' open')
        return True
    else:
        return False

# if __name__ == '__main__':
#         get_alive_Hosts()
# #     scan_port('10.127.188.192',445)
